package com.shuizhu.redisson.controller;

import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RedisLockController {
    @Autowired
    private RedissonClient redisson;
    //读写锁
    public static final String READ_WRITE_LOCK_KEY = "READ_WRITE_LOCK_KEY";

    @GetMapping("writeLock")
    public String writeLock(){
        RReadWriteLock readWriteLock = redisson.getReadWriteLock(READ_WRITE_LOCK_KEY);
        try {
            //写锁
            readWriteLock.writeLock().lock();
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            readWriteLock.writeLock().unlock();
        }
        return "读写锁=>写完毕";
    }

    @GetMapping("readLock")
    public String readLock(){
        RReadWriteLock readWriteLock = redisson.getReadWriteLock(READ_WRITE_LOCK_KEY);
        try {
            //读锁
            readWriteLock.readLock().lock();
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            readWriteLock.readLock().unlock();
        }
        return "读写锁=>读完毕";
    }
}
